<?php

class pdfgen {

	private $rawHTML;
	private $filePointer;
	private $outputFilePointer;
	private $runtimeOptions = array("layout" => "Portrait", "size" => "A4");
	private $runCommand;
	private $uniqueID = -1;
	private $formatter;

	public function __construct(array $options = array()){
		$this->runtimeOptions = array_merge($this->runtimeOptions, $options);
		
		// Generate a unique ID for this PDF.
		$this->uniqueID = md5(time() . rand(0, 999));
		
		while (file_exists(SYS_TMPDIR . "PDF/{$this->uniqueID}.pdf" )){
			$this->uniqueID = md5(time() . rand(0, 999));
		}
		
		// Formatting options
		$this->formatter = isset($options['formatter']) ? $options['formatter'] : new defaultFormat;
		
		// Does the class extend printFormatter?
		if( is_subclass_of($this->formatter, 'printFormatter') == false) throw new PicBoardException("Formatter passed is not a printFormatter");
		
		// Overrides? Applicable for default only.
		if($this->runtimeOptions['layout'] != "" && get_class($this->formatter) == "defaultFormat") $this->formatter->orientation = $this->runtimeOptions['layout'];
		if($this->runtimeOptions['size'] != "" && get_class($this->formatter) == "defaultFormat") $this->formatter->pageSize = $this->runtimeOptions['size'];
				
		$this->runCommand = SYS_LIBDIR . "wkhtmltopdf-i386 " . $this->formatter->getConfig() . " --quiet --disable-smart-shrinking --zoom 2 '" . SYS_TMPDIR . "PDF/{$this->uniqueID}.html' '" . SYS_TMPDIR . "PDF/{$this->uniqueID}.pdf'";
	}

	private function writeHTMLFile($data){
		$this->rawHTML = $data;
		file_put_contents(SYS_TMPDIR . "PDF/{$this->uniqueID}.html", $data);
	}

	private function writePDFFile(){
		$cmd = escapeshellcmd( $this->runCommand );
		$output = passthru($cmd, $rtn);
	}

	private function cleanUp(){
		unlink(SYS_TMPDIR . "PDF/{$this->uniqueID}.html");
		unlink(SYS_TMPDIR . "PDF/{$this->uniqueID}.pdf");
	}

	public function from_html($data){
		$this->writeHTMLFile( $data );
	}
	
	public function from_file($data){
		$this->writeHTMLFile( file_get_contents($data) );
	}

	public function stream($name){

		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: public"); 
		header("Content-Description: File Transfer"); 
		header("Content-Type: application/pdf"); 
		header('Content-Disposition: attachment; filename="' . $name . '"');
		header("Content-Transfer-Encoding: binary");
	
		readfile(SYS_TMPDIR . "PDF/{$this->uniqueID}.pdf");
	
		$this->cleanUp();
	}
	
	public function convert(){
		$this->writePDFFile();
	}

}

?>